﻿using Microsoft.EntityFrameworkCore;
using WorkflowCore.Interface;
using Yuekao.API.Write.CommandHander;
using Yuekao.Domain.BaseReposi;
using Yuekao.Domain.Entitys;

namespace Yuekao.API.Write
{
    public static class WorkflowStart
    {
        public static void UseWorkflow(this WebApplication app)
        {
            var host = app.Services.GetService<IWorkflowHost>()!;

            app.Lifetime.ApplicationStarted.Register(() =>
            {
                host.Start();

                var scope=app.Services.CreateScope().ServiceProvider;

                var definition = scope.GetService<IBaseRepository<WorkflowDefinitionModel>>()!;
                var service = scope.GetService<DefinitionAddCommandHandler>()!;

                var list = definition.GetAll().AsNoTracking().ToList();

                foreach (var item in list)
                {
                    service.Location(item);
                }

            });

            app.Lifetime.ApplicationStopping.Register(() =>
            {
                host.Stop();
            });
        }
    }
}
